import {getStudentUsers} from '@/api/user.js'
import {ref, watch} from "vue";
import {useRoute} from "vue-router";
import {getProjectDetail, getSubmissions} from "@/api/projects.js";
import {createAssignment, createSubmission} from "@/api/assignment.js";
import {useUserStore} from "@/stores/user.js";
import {message} from "ant-design-vue";

const DEFAULT_STEPS = ['项目目标及意义', '技术选型', '系统分析', '系统设计', '系统实现', '系统测试']

function getStatusString(status) {
    switch (status) {
        case 'PENDING':
            return '已提交'
        case 'REJECTED':
            return '已驳回'
        case 'APPROVED':
            return '已通过'
        default:
            return '未提交'
    }
}

function getClazz(status) {
    // 根据不同情况，返回 success error 等
    switch (status) {
        case 'PENDING':
            return 'success'
        case 'REJECTED':
            return 'error'
        case 'APPROVED':
            return 'success'
        default:
            return 'check'
    }
}

export function useAssignment() {
    const route = useRoute();
    const userOptions = ref([]);
    const loading = ref(true);
    const error = ref(null);
    const project = ref({})
    const isMemberEditable = ref(false)
    const submitDescription = ref('')
    const currentStep = ref("")
    const submissions = ref([])
    const isSubmissionEditable = ref(false)
    const uploadedFiles = ref([])
    const progressSteps = ref([])

    const { userId } = useUserStore()

    const updateProject = async (id) => {
        try {
            const projResp = await getProjectDetail(id)
            const leader = projResp.assignment?.teamMembers.find(it => it.teamRole === 'TEAM_LEAD').userId
            const members = projResp.assignment?.teamMembers.filter(it => it.teamRole === 'TEAM_MEMBER').map(it => it.userId)
            isMemberEditable.value = projResp.status === 'CREATED'
            project.value = {...projResp, leader, members}
            console.log('project', project.value)
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }

    const updateSubmissions = async (id) => {
        try {
            const resp = await getSubmissions(id)
            submissions.value = resp
            // 注意遍历steps，若能在submissions中找item.type不存在，或者其状态被REJECT, 则 currentStep 为这个step
            progressSteps.value = []
            for (let i = 0; i < DEFAULT_STEPS.length; i++) {
                const item = resp.find(it => it.type === DEFAULT_STEPS[i])
                if (!item || 'REJECTED' === item.status) {
                    currentStep.value = DEFAULT_STEPS[i]
                    break
                }
            }
            for (let i = 0; i < DEFAULT_STEPS.length; i++) {
                const item = resp.find(it => it.type === DEFAULT_STEPS[i])
                progressSteps.value.push({
                    title: DEFAULT_STEPS[i],
                    isActive: currentStep.value === DEFAULT_STEPS[i],
                    createdAt: item?.submissionTime || '',
                    status: getStatusString(item?.reviewStatus),
                    rawStatus: item?.reviewStatus || 'NA'
                })
            }



            console.log('progressSteps', progressSteps.value)
            console.log('resp', resp)
            isSubmissionEditable.value = '完成' !== currentStep.value
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }

    // 监听 route changes 获取 id 参数，立即的
    watch(() => route.params.id, async (newId) => {
        if (!newId) {
            return;
        }
        try {
            await updateProject(newId)
            await updateSubmissions(newId)
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }, {immediate: true})

    // Create a function to load the data
    const loadUsers = async () => {
        try {
            loading.value = true;
            error.value = null;
            const resp = await getStudentUsers();
            userOptions.value = resp.students.map(it => ({
                label: it.realName,
                value: it.id
            }));
        } catch (err) {
            error.value = err;
            console.error('Failed to load users:', err);
        } finally {
            loading.value = false;
        }
    };

    async function handleSubmitSubmission() {
        loading.value = true;
        if(isMemberEditable.value) {
            await createAssignment(project.value.id, {
                teamLeadId: project.value.leader,
                teamMemberIds: project.value.members,
            })
        }
        await createSubmission(project.value.id, {
            description: submitDescription.value,
            type: currentStep.value,
            submitterId: localStorage.getItem('userId'),
            file: uploadedFiles.value[0],
        })
        await updateSubmissions(project.value.id)
        message.success('提交成功')
        loading.value = false;
    }

    function handleFileSelect (e) {
        uploadedFiles.value[0] = e.target.files[0]
    }

    // Initial load
    loadUsers();

    return {
        userOptions,
        loading,
        error,
        project,
        isMemberEditable,
        submitDescription,
        submissions,
        currentStep,
        uploadedFiles,
        handleSubmitSubmission,
        handleFileSelect,
        progressSteps,
    };
}